package org.min.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import org.min.exception.ProjectNotFoundException;

/**
 * 
 * @ClassName: LineCounter
 * @Description: 行数计算器
 * @author minjun
 * 
 */
public class LineCounter {

	/** 文件后缀 */
	private List<String> suffix;

	/** 行数 */
	private int line;

	private LineCounter(String basePath, String... suffix) {
		this.suffix = Arrays.asList(suffix);
		File file = new File(basePath);
		if (!file.exists()) {
			throw new ProjectNotFoundException("没有找到该项目");
		}
		count(file);
	}

	/**
	 * 
	 * @Title: lineCount
	 * @Description: 获取行数
	 * @param @return 设定文件
	 * @return int 返回类型
	 * @throws
	 */
	public int lineCount() {
		return line;
	}

	/**
	 * 
	 * @Title: count
	 * @Description: 递归计算行数
	 * @param @param file
	 * @param @param level
	 * @param @return 设定文件
	 * @throws
	 */
	private void count(File file) {
		// 如果没有元素就返回
		File[] files = file.listFiles();
		for (File child : files) {
			if (child.isDirectory()) {
				// 如果是目录，继续递归
				count(child);
			} else if (isPermittedFile(child)) {
				// 如果是指定格式文件，则计算里面的代码行数
				readFileAndCountLine(child);
			}
		}
	}

	private void readFileAndCountLine(File child) {
		InputStream in = null;
		try {
			in = new FileInputStream(child);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(in));

		try {
			while (br.readLine() != null) {
				line++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private boolean isPermittedFile(File file) {
		if (file == null)
			throw new IllegalArgumentException("非法参数");
		if (!file.isFile())
			return false;
		if (suffix == null||suffix.isEmpty())
			return true;
		
		String name = file.getName();
		
		//获取后缀
		String s=name.substring(name.lastIndexOf(".")+1);
		
		if(!suffix.contains(s)){
			return false;
		}
		
		return true;
	}

	public static LineCounter getCounter(String basePath, String... suffix) {
		return new LineCounter(basePath, suffix);
	}

}
